package org.grottarossa.ui.core.controls.skiptask;

import java.util.ArrayList;
import java.util.ResourceBundle;

import org.grottarossa.template.data.pojo.tasks.Task;
import org.grottarossa.template.drivers.DriverException;
import org.grottarossa.ui.core.ApplicationSession;

/***
 * Gestisce la logica del controllo per lo skip di un task
 * @author 
 *
 */
public class SkipTaskPresenter
{
	private final ResourceBundle m_localizer;

	/*** View ***/
	private final SkipTask m_view;

	/*** Listeners ***/
	private ArrayList<ISkipTaskListener> m_listeners = new ArrayList<ISkipTaskListener>();

	/*** Stato della maschera di skip task ***/
	private SkipTaskData m_data;

	/*** Task di riferimento ***/
	private final Task m_task;

	private final ApplicationSession m_appSession;

	public SkipTaskPresenter(ApplicationSession appSession, SkipTask view, ResourceBundle localizer, Task task)
	{
		this.m_appSession = appSession;
		this.m_view = view;
		this.m_localizer = localizer;
		this.m_task = task;
		m_view.setPresenter(this);
	}

	public void initialize()
	{
		m_data = new SkipTaskData();
		m_data.setTaskname(m_task.getTaskName());
		m_data.setComment(m_task.getComments() == null ? "" : m_task.getComments());
		m_view.setSkipTaskData(m_data);
	}

	/***
	 * Esegue lo skip del task di riferimento e notifica l'operazione ai listeners
	 */
	public void ok()
	{
		if(m_data.getComment() == null || m_data.getComment().trim().equals(""))
		{
			m_view.showWarning(m_localizer.getString("form.messages.selectvalue"));
			return;
		}

		try
		{
			m_task.setComments(m_data.getComment());
			m_appSession.getBuilder().getCaseManagement().skipTask(m_task);
		}
		catch(DriverException ex)
		{
			m_view.showError(m_localizer.getString("form.messages.skiperror"));
			return;
		}


		for(ISkipTaskListener l : m_listeners)
		{
			l.ok(m_data);
		}
	}

	/***
	 * Notifica ai listeners l'annullamento dell'operazione
	 */
	public void cancel()
	{
		for(ISkipTaskListener l : m_listeners)
		{
			l.cancel();
		}
	}

	/***
	 * Aggiunge un listener
	 * @param listener
	 */
	public void addListener(ISkipTaskListener listener)
	{
		m_listeners.add(listener);
	}

}
